<template>
  <div class="p-3 w-full">
    <div class="flex justify-between mb-2">
      <div>
        <el-button class="button_normal" type="primary" @click="addOpenForm"
          >添加</el-button
        >
      </div>
      <div class="flex">
        <el-input
          type="text"
          v-model="searchValue"
          style="width: 300px"
          clearable
          @change="loadTable({ title: searchValue })"
          placeholder="轮播图标题"
          :prefix-icon="Search"
        >
        </el-input>
        <!-- <el-button
          @click="loadTable({ name: searchValue })"
          type="primary"
          size="large"
          >搜索</el-button
        > -->
      </div>
    </div>
    <el-table :data="list" width="100%" v-loading="loading">
      <el-table-column
        prop="id"
        sortable
        label="编号"
        width="100px"
        align="center"
      />
      <el-table-column prop="title" label="轮播图标题" align="center" />
      <el-table-column prop="comicName" label="漫画名" align="center" />
      <el-table-column label="封面" width="80px" align="center">
        <template #default="scope">
          <el-image
            :src="'http://localhost:8181' + scope.row.picture"
            :zoom-rate="1.2"
            :preview-src-list="['http://localhost:8181' + scope.row.picture]"
            fit="cover"
          />
          <!-- <el-avatar :src="'http://localhost:8181/' + scope.row.cover" /> -->
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300px" align="center">
        <template #default="scope">
          <el-popconfirm @confirm="deleteData(scope.row.id)" title="确定删除？">
            <template #reference>
              <el-button size="small" class="button_delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small
      background
      layout="prev, pager, next"
      :total="total"
      class="mt-4"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      @current-change="currentChange"
    />
    <el-dialog
      v-model="dialogVisible"
      :title="!isUpdate ? '添加' : '编辑'"
      @close="resetForm(formRef)"
      width="30%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        size="default"
        status-icon
      >
        <el-form-item label="轮播图标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="漫画名" prop="comicName">
          <el-input v-model="form.comicName" />
        </el-form-item>
        <el-form-item label="轮播图" prop="picture">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            @change="fileOnChange"
            :limit="1"
          >
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="isUpdate ? update(formRef) : add(formRef)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import request from "@/api/http";
import { useRouter, useRoute } from "vue-router";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import productionDetail from "@/components/productionDetail.vue";
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const list = ref([]);
const pageNum = ref(1);
const pageSize = ref(8);
const total = ref(0);
const searchValue = ref("");
const isUpdate = ref(false);
const formRef = ref(null);
const form = ref({
  title: "",
  comicName: "",
  picture: "",
});
const initForm = {
  title: "",
  comicName: "",
  picture: "",
};
const options = [
  {
    value: "1",
    label: "玄幻",
  },
  {
    value: "2",
    label: "言情",
  },
  {
    value: "3",
    label: "城市",
  },
  {
    value: "4",
    label: "灵异",
  },
  {
    value: "5",
    label: "科幻",
  },
  {
    value: "6",
    label: "其他",
  },
];
const rules = ref({
  title: [
    {
      required: true,
      message: "请输入轮播图标题",
      trigger: "blur",
    },
  ],
  comicName: [
    {
      required: true,
      message: "请输入漫画名称",
      trigger: "blur",
    },
  ],
  picture: [
    {
      required: true,
      message: "请上传轮播图",
      trigger: "blur",
    },
  ],
});
onMounted(() => {
  loadTable();
});
const loadTable = (
  data = {
    // type: "玄幻",
    // "author":"唐家三少",
    // name: value,
  }
) => {
  loading.value = true;
  request({
    url: "carousel/getAllCarousel",
    method: "post",
    data: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      data: data,
    },
  }).then((res) => {
    // console.log(res);
    if (res.code == 200) {
      list.value = res.data.records;
      total.value = res.data.total;
      loading.value = false;
    }
  });
};
const currentChange = (value) => {
  loadTable();
};
const dialogVisible = ref(false);
const deleteData = (id) => {
  request.post("carousel/deleteCarousel", { id }).then((res) => {
    if (res.code == 200) {
      ElMessage.success("删除成功！");
      loadTable();
    } else {
      ElMessage.error("系统错误！");
    }
  });
};
const add = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log(form.value);
      let FormFile = new FormData();
      FormFile.append("picture", form.value.picture);
      let copyForm = { ...form.value };
      Reflect.deleteProperty(copyForm, "picture");
      // console.log(copyForm, 90);
      FormFile.append(
        "carousel",
        new Blob([JSON.stringify(copyForm)], { type: "application/json" })
      );
      // console.log(FormFile, 9090);
      request({
        url: "carousel/addCarousel",
        method: "post",
        isFile: true,
        data: FormFile,
      }).then((res) => {
        if (res.code == 200) {
          ElMessage.success("添加成功！");
          dialogVisible.value = false;
          loadTable();
        } else {
          ElMessage.error("添加失败");
        }
      });
    }
  });
};
const update = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log(form.value);
      let FormFile = new FormData();
      FormFile.append("coverFile", form.value.cover);
      let copyForm = { ...form.value };
      Reflect.deleteProperty(copyForm, "cover");
      FormFile.append(
        "comic",
        new Blob([JSON.stringify(copyForm)], { type: "application/json" })
      );
      request({
        url: "comic/updateComic",
        method: "post",
        isFile: true,
        data: FormFile,
      }).then((res) => {
        if (res.code == 200) {
          ElMessage.success("编辑成功！");
          dialogVisible.value = false;
          loadTable();
        } else {
          ElMessage.error("编辑失败");
        }
      });
    }
  });
};
const addOpenForm = () => {
  form.value = initForm;
  isUpdate.value = false;
  dialogVisible.value = true;
};
const fileOnChange = (data) => {
  form.value.picture = data.raw;
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
